package cn.edu.Bistu.wordsbook;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/*   仍未实现或存在的问题：
 *   横屏时没实现长按弹出上下文菜单
 *   横屏时添加单词列表没能实时更新
 *   横屏时搜索单词得到的结果是竖屏时的ListView的，这导致横屏搜索结果没能左右分屏
 *   没实现在线查询
 *   没实现生词本
 *   界面美观性待提高
 *   ......
 *
 *
 */


public class MainActivity extends AppCompatActivity {
    WordsDBHelper mDbHelper;   //用来创建或打开数据库

    //开启fragment事务的变量
    FragmentManager mFragmentManager;
    FragmentTransaction mFragmentTransaction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //获取activity_main的控件
        LinearLayout layout1 = findViewById(R.id.wordsFrag);
        LinearLayout layout2 = findViewById(R.id.detailsFrag);
        ListView wordsList = findViewById(R.id.word_list);

        //为ListView注册上下文菜单
        registerForContextMenu(wordsList);
        //创建SQLiteOpenHelper对象，第一次运行时数据库并没有被创建
        mDbHelper = new WordsDBHelper(this);

        //通过控件的visibility来实现横竖屏的效果
        if (!isLand()) {


            //在列表显示全部单词
            ArrayList<Map<String, String>> items = getAllWords();
            setWordsListView(items);

            layout1.setVisibility(View.GONE);
            layout2.setVisibility(View.GONE);
            wordsList.setVisibility(View.VISIBLE);

        } else {
            wordsList.setVisibility(View.GONE);
            layout1.setVisibility(View.VISIBLE);
            layout2.setVisibility(View.VISIBLE);

            refreshListFragment();

        }


    }

    //刷新fragment列表
    public void refreshListFragment() {
        mFragmentManager = getSupportFragmentManager();
        mFragmentTransaction = mFragmentManager.beginTransaction();
        mFragmentTransaction.replace(R.id.wordsFrag, WordsFragment.newInstance(getAllWords())).commit();

    }

    //activity销毁时关闭数据库
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDbHelper != null)
            mDbHelper.close();
    }

    //判断是否横屏
    public boolean isLand() {
        return getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
    }


    //生成长按单词时的上下文菜单
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        getMenuInflater().inflate(R.menu.contextmenu_listview, menu);
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        TextView textId = null;
        TextView textWord = null;
        TextView textMeaning = null;
        TextView textSample = null;

        AdapterView.AdapterContextMenuInfo info = null;
        View itemView = null;

        switch (item.getItemId()) {
            case R.id.menu_delete:
                info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
                itemView = info.targetView;
                textId = itemView.findViewById(R.id.textId);
                if (textId != null) {
                    String strId = textId.getText().toString();
                    DeleteDialog(strId);
                }
                break;
            case R.id.menu_update:
                info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
                itemView = info.targetView;
                textId = itemView.findViewById(R.id.textId);
                textWord = itemView.findViewById(R.id.textWord);
                textMeaning = itemView.findViewById(R.id.textMeaning);
                textSample = itemView.findViewById(R.id.textSample);
                if (textId != null && textWord != null && textMeaning != null && textSample != null) {
                    String strID = textId.getText().toString();
                    String strWord = textWord.getText().toString();
                    String strMeaning = textMeaning.getText().toString();
                    String strSample = textSample.getText().toString();
                    UpdateDialog(strID, strWord, strMeaning, strSample);

                }
                break;

        }
        refreshListFragment();
        return true;
    }

    //使用sql语句查找单词
    private ArrayList<Map<String, String>> SearchSql(String strSearch) {
        SQLiteDatabase db = mDbHelper.getReadableDatabase();

        String sql = "select * from words where word like ? order by word desc";
        Cursor c = db.rawQuery(sql, new String[]{"%" + strSearch + "%"});
        return ConvertCursorToList(c);
    }


    //将查询得到的Cursor指向的数据转换为list类型
    @SuppressLint("Range")
    private ArrayList<Map<String, String>> ConvertCursorToList(Cursor c) {
        ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();

        while (c.moveToNext()) {
            Map<String, String> map = new HashMap<String, String>();
            map.put(Words.Word._ID, c.getString(c.getColumnIndex(Words.Word._ID)));
            map.put(Words.Word.COLUMN_WORD, c.getString(c.getColumnIndex(Words.Word.COLUMN_WORD)));
            map.put(Words.Word.COLUMN_MEANING, c.getString(c.getColumnIndex(Words.Word.COLUMN_MEANING)));
            map.put(Words.Word.COLUMN_SAMPLE, c.getString(c.getColumnIndex(Words.Word.COLUMN_SAMPLE)));
            list.add(map);

        }
        return list;

    }

    //使用sql语句更新单词
    private void UpdateSql(String strID, String strWord, String strMeaning, String strSample) {
        SQLiteDatabase db = mDbHelper.getReadableDatabase();
        String sql = "update words set word=?,meaning=?,sample=? where _id=?";
        db.execSQL(sql, new String[]{strWord, strMeaning, strSample, strID});

    }

    //使用sql语句删除单词
    private void DeleteSql(String strID) {
        String sql = "delete from words where _id='" + strID + "'";
        SQLiteDatabase db = mDbHelper.getReadableDatabase();
        db.execSQL(sql);

    }

    //使用sql语句插入单词
    private void InsertSql(String strWord, String strMeaning, String strSample) {
        String strSql = "insert into words(word,meaning,sample) values(?,?,?)";

        SQLiteDatabase db = mDbHelper.getWritableDatabase();
        db.execSQL(strSql, new String[]{strWord, strMeaning, strSample});

    }


    private void UpdateDialog(final String strID, final String strWord, final String strMeaning, final String strSample) {
        final LinearLayout linearLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_insert, null);

        //初始化弹出框中原单词的内容
        ((EditText) linearLayout.findViewById(R.id.txtWord)).setText(strWord);
        ((EditText) linearLayout.findViewById(R.id.txtMeaning)).setText(strMeaning);
        ((EditText) linearLayout.findViewById(R.id.txtSample)).setText(strSample);

        new AlertDialog.Builder(this)
                .setTitle("修改单词")
                .setView(linearLayout)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        String newWord = ((EditText) linearLayout.findViewById(R.id.txtWord)).getText().toString();
                        String newMeaning = ((EditText) linearLayout.findViewById(R.id.txtMeaning)).getText().toString();
                        String newSample = ((EditText) linearLayout.findViewById(R.id.txtSample)).getText().toString();


                        UpdateSql(strID, newWord, newMeaning, newSample);
                        ArrayList<Map<String, String>> items = getAllWords();
                        setWordsListView(items);

                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                })
                .create()
                .show();

    }

    //生成菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.menu_insert:
                InsertDialog();
                refreshListFragment();
                return true;
            case R.id.menu_search:
                SearchDialog();
                return true;
            case R.id.menu_help:
                HelpDialog();
                return true;

        }

        return super.onOptionsItemSelected(item);
    }

    //搜索单词对话框
    private void SearchDialog() {


        final LinearLayout linearLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_search, null);
        new AlertDialog.Builder(this)
                .setTitle("查询单词")
                .setView(linearLayout)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String txtSearchWord = ((EditText) linearLayout.findViewById(R.id.txtSearchWord)).getText().toString();
                        ArrayList<Map<String, String>> items = null;
                        items = SearchSql(txtSearchWord);

                        if (items.size() > 0) {
                            Bundle bundle = new Bundle();
                            //将找到的单词列表封装成束利用intent传给SearchActivity，在SearchActivity中显示结果
                            bundle.putSerializable("result", items);
                            Intent intent = new Intent(MainActivity.this, SearchActivity.class);
                            intent.putExtras(bundle);
                            startActivity(intent);

                        } else
                            Toast.makeText(MainActivity.this, "没有找到单词", Toast.LENGTH_LONG).show();


                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                })
                .create()
                .show();

    }

    //插入单词对话框
    private void InsertDialog() {

        final LinearLayout linearLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_insert, null);
        new AlertDialog.Builder(this)
                .setTitle("添加单词")
                .setView(linearLayout)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        String strWord = ((EditText) linearLayout.findViewById(R.id.txtWord)).getText().toString();
                        String strMeaning = ((EditText) linearLayout.findViewById(R.id.txtMeaning)).getText().toString();
                        String strSample = ((EditText) linearLayout.findViewById(R.id.txtSample)).getText().toString();


                        InsertSql(strWord, strMeaning, strSample);
                        ArrayList<Map<String, String>> items = getAllWords();
                        setWordsListView(items);

                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                })
                .create()
                .show();

    }

    //删除单词对话框
    private void DeleteDialog(final String strId) {
        new AlertDialog.Builder(this)
                .setTitle("删除单词")
                .setMessage("确认删除单词？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        DeleteSql(strId);
                        setWordsListView(getAllWords());
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                })
                .create()
                .show();

    }

    //弹出帮助的对话框
    private void HelpDialog() {
        AlertDialog.Builder helpTxt = new AlertDialog.Builder(this);
        helpTxt.setMessage("这里是帮助文档\n本单词本由Dio开发").setTitle("Help");
        helpTxt.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        helpTxt.show();
    }

    //设置适配器显示单词
    private void setWordsListView(ArrayList<Map<String, String>> items) {

        if (items != null) {
            SimpleAdapter adapter = new SimpleAdapter(this, items, R.layout.listview_item
                    , new String[]{Words.Word._ID, Words.Word.COLUMN_WORD, Words.Word.COLUMN_MEANING, Words.Word.COLUMN_SAMPLE}
                    , new int[]{R.id.textId, R.id.textWord, R.id.textMeaning, R.id.textSample});
            ListView list = findViewById(R.id.word_list);
            list.setAdapter(adapter);
        }
    }

    //获取数据库里的所有单词
    private ArrayList<Map<String, String>> getAllWords() {
        if (mDbHelper == null) {
            Log.i("MyTag", "Error!");
            return null;
        }
        SQLiteDatabase db = mDbHelper.getReadableDatabase();

        String projection[] = new String[]{Words.Word._ID, Words.Word.COLUMN_WORD,
                Words.Word.COLUMN_MEANING, Words.Word.COLUMN_SAMPLE};
        String order = Words.Word.COLUMN_WORD + " DESC";

        Cursor cursor = db.query(Words.Word.TABLE_NAME, projection, null, null, null, null,
                order);


        return ConvertCursorToList(cursor);
    }
}